﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;

namespace Nomad.ASPMVVM {
    public abstract class PageViewModel: INotifyPropertyChanged {
        private readonly IDictionary<string, object> propertyValues = new Dictionary<string, object>();

        protected HttpRequest Request {
            get {
                return HttpContext.Current.Request;
            }
        }
        protected HttpResponse Response {
            get {
                return HttpContext.Current.Response;
            }
        }
        protected HttpServerUtility Server {
            get {
                return HttpContext.Current.Server;
            }
        }

        public event EventHandler<PropertyChangedEventArgs> PropertyChanged;

        public abstract void InitializeProperties();

        protected virtual void OnPropertyChanged(string propertyName) {
            var handler = this.PropertyChanged;
            if (handler != null) {
                handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected TValue GetValue<TValue>(string propertyName) {
            if (propertyValues.ContainsKey(propertyName)) {
                return (TValue)propertyValues[propertyName];
            }

            return default(TValue);
        }
        protected void SetValue<TValue>(string propertyName, TValue value) {
            var currentValue = this.GetValue<TValue>(propertyName);
            if (Object.Equals(currentValue, value) == false) {
                this.ClearValue(propertyName);
                this.propertyValues.Add(propertyName, value);
                this.OnPropertyChanged(propertyName);
            }
        }
        protected void ClearValue(string propertyName) {
            if (propertyValues.ContainsKey(propertyName)) {
                propertyValues.Remove(propertyName);
            }
        }
    }
}
